//
//  CTAppUpdate.m
//  ConstellationTalk_0.1
//
//  Created by riley on 15/5/11.
//  Copyright (c) 2015年 riley chu. All rights reserved.
//

#import "CTAppUpdate.h"
#import "CTDebugManager.h"
#import "CTTextManager.h"
#import "CTAppLanguage.h"
#import "CTLogin.h"
#import "CTRequestUtil.h"
#import "CTFile.h"
#import "CTRequestErrorCode.h"
#import "CTUrl.h"
#import "CTDeviceFunction.h"
#import "CTAppUpdateItem.h"




@implementation CTAppUpdate



//请求更新参数
+(void)checkAppUpdateWithForceUpdateHandler:(CTAppUpadateForceUpdate)forceUpdateBlock
                        CommonUpdateHandler:(CTAppUpadateCommonUpdate)commonUpdateBlock
                          NoneUpdateHandler:(CTAppUpadateNoneUpdate)noneUpdateBlock
{
    
    __block CTAppUpdateItem * versionInfoItem;
    NSString * url = CT_URL_APP_VERSION_UPDATE(version);
    
    NSString * languageStr = [CTAppLanguage systemLanguage];
    
    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithCapacity:0];
    @try {
        NSString * postToken = [CTLogin token];
        [param setObject:postToken forKey:@"token"];
        [param setObject:@"2" forKey:@"type"];
        if ([languageStr isEqualToString:@"zh-Hans"])[param setObject:@"cn" forKey:@"lang"];
        else [param setObject:@"en" forKey:@"lang"];
        if ([CTLogin isUserLoginState] == NO)[param setObject:@"visitor" forKey:@"visitor"];
        else [param setObject:@"user" forKey:@"visitor"];

    }
    @catch (NSException *exception) {
        [CTDebugManager showErrorLogInfo:@"组装app更新请求参数失败!!"];
    }
    
    [CTRequestUtil sendAsyGetRequest:url withParam:param withCompletionSuccessHandler:^(NSData *data) {
        versionInfoItem = [self parserData:data];
        if (versionInfoItem != nil) {
            //success
            
            @try {
                //判断当前本地是否存在versionInfoPlist文件
                if ([CTFile isExistFile:@"appVersionInfo.plist" doc:CTFileDocDocuments path:@"appVersion"]) {
                    //存在
                    NSMutableDictionary * localVersionInfoDic = [CTFile getDicFile:@"appVersionInfo.plist" fromDoc:CTFileDocDocuments fromPath:@"appVersion"];
                    NSDictionary * infoDic = [localVersionInfoDic objectForKey:@"info"];
                    NSString * localVersion = [NSString stringWithFormat:@"%@",[infoDic objectForKey:@"ver"]];
                    
                    if ([infoDic objectForKey:@"ver"] == nil) {
                        
                        //不存在
                        NSError * error;
                        
                        id jsonObject = [NSJSONSerialization
                                         JSONObjectWithData:data
                                         options:NSJSONReadingAllowFragments
                                         error:&error];
                        if (jsonObject != nil && error == nil){
                            if ([jsonObject isKindOfClass:[NSDictionary class]]){
                                NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;
                                //存入文件
                                //versionInfo:
                                [CTFile cacheDicFile:[deserializedDictionary mutableCopy]
                                            fileName:@"appVersionInfo.plist"
                                             saveDoc:CTFileDocDocuments
                                            savePath:@"appVersion"];
                            }
                        }
                        noneUpdateBlock();
                        
                    }
                    else
                    {
                        if (![versionInfoItem.ver isEqualToString:localVersion]) {
                            if ([versionInfoItem.status isEqualToString:@"0"]) {
                                //common update
                                commonUpdateBlock(versionInfoItem);
                            }
                            else if([versionInfoItem.status isEqualToString:@"1"])
                            {
                                //force update
                                forceUpdateBlock(versionInfoItem);
                            }
                            else
                            {
                                [CTDebugManager showErrorLogInfo:@"判断是否为强制更新是出现错误！！！"];
                                noneUpdateBlock();
                            }
                        }
                        else
                        {
                            noneUpdateBlock();
                        }
                    }
                    
                }
                else {
                    //不存在
                    NSError * error;
                    
                    id jsonObject = [NSJSONSerialization
                                     JSONObjectWithData:data
                                     options:NSJSONReadingAllowFragments
                                     error:&error];
                    if (jsonObject != nil && error == nil){
                        if ([jsonObject isKindOfClass:[NSDictionary class]]){
                            NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;
                            //存入文件
                            //versionInfo:
                            [CTFile cacheDicFile:[deserializedDictionary mutableCopy]
                                        fileName:@"appVersionInfo.plist"
                                         saveDoc:CTFileDocDocuments
                                        savePath:@"appVersion"];
                        }
                        
                        noneUpdateBlock();
                    }
                }
            }
            @catch (NSException *exception) {
                noneUpdateBlock();
            }
            
        }
        else
        {
            //failed
            [CTDebugManager showErrorLogInfo:@"版本信息数据请求失败!!"];
            noneUpdateBlock();
        }
    } withFailedHandler:^(NSError *error) {
        //failed
        
        [CTDebugManager showErrorLogInfo:@"版本信息数据请求失败!!"];
        noneUpdateBlock();
    }];
    
}



#pragma mark - data parser -
//解析
+(CTAppUpdateItem *)parserData:(NSData *)resultData
{
    
    CTAppUpdateItem *  itm;
    
    @try {
        
        NSError * error;
        
        id jsonObject = [NSJSONSerialization
                         JSONObjectWithData:resultData
                         options:NSJSONReadingAllowFragments
                         error:&error];
        if (jsonObject != nil && error == nil){
            
            if ([jsonObject isKindOfClass:[NSDictionary class]]){
                
                NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;
                NSString * errCode = [NSString stringWithFormat:@"%@",(NSString *)[deserializedDictionary objectForKey:@"error_code"]];
                if ([errCode isEqualToString:@"0"]) {
                    
                    itm = [[CTAppUpdateItem alloc] init];
                    
                    NSDictionary * infoDic = [deserializedDictionary objectForKey:@"info"];
                   
                    itm.name =[NSString stringWithFormat:@"%@", [infoDic objectForKey:@"name"]];
                    itm.url = [NSString stringWithFormat:@"%@", [infoDic objectForKey:@"url"]];
                    itm.describe = [NSString stringWithFormat:@"%@", [infoDic objectForKey:@"describe"]];
                    itm.status = [NSString stringWithFormat:@"%@", [infoDic objectForKey:@"status"]];
                    itm.ver = [NSString stringWithFormat:@"%@", [infoDic objectForKey:@"ver"]];
                    itm.timestamp = [NSString stringWithFormat:@"%@", [infoDic objectForKey:@"timestamp"]];
                    
                    
                }
                else{
                    
                    [CTDebugManager showErrorLogInfo:[CTRequestErrorCode errDescription:errCode]];
                }
            }
        }
        else
        {
            [CTDebugManager showErrorLogInfo:@"解析更新数据错误！"];
        }
    }
    @catch (NSException *exception) {
        [CTDebugManager showErrorLogInfo:@"解析更新数据错误！"];
    }
    
    return itm;
    
}

@end
